package com.mingtu.guards.activity;

import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.StringUtils;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.center.adapter.DepartmentAdapter;
import com.mingtu.center.bean.DeptNameBean;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.adapter.MyFragmentPagerAdapter;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.entity.TabEntity;
import com.mingtu.common.utils.CalendarPickerUtils;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.common.view.MyAutofitTextView.AutofitTextView;
import com.mingtu.guards.R;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.AllTrackRecordBean;
import com.mingtu.guards.fragment.AllSignInRecordFragment;
import com.mingtu.guards.fragment.AllTrackRecordFragment;
import com.mingtu.guards.utils.MyConstant;
import com.mingtu.guards.view.FilterCancleView;
import com.mingtu.guards.view.FilterSureView;
import com.mingtu.guards.view.TimeFilterView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class RecordActivity extends MyBaseActivity {


    @BindView(R.id.common_tab)
    CommonTabLayout commonTab;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.tv_fold_depart)
    TextView tvFoldDepart;
    @BindView(R.id.layout_arrow_depart)
    LinearLayout layoutArrowDepart;
    @BindView(R.id.recycler_depart)
    RecyclerView recyclerDepart;
    @BindView(R.id.layout_right_drawer)
    RelativeLayout layoutRightDrawer;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.tv_total_mileage)
    AutofitTextView tvTotalMileage;
    @BindView(R.id.tv_total_time)
    AutofitTextView tvTotalTime;
    @BindView(R.id.tv_total_day_num)
    AutofitTextView tvTotalDayNum;
    @BindView(R.id.tv_total_sign_in_num)
    AutofitTextView tvTotalSignInNum;
    @BindView(R.id.coordinator)
    CoordinatorLayout coordinator;
    @BindView(R.id.time_filter_time)
    TimeFilterView timeFilterTime;
    @BindView(R.id.filter_cancle_view)
    FilterCancleView filterCancleView;
    @BindView(R.id.filter_sure_view)
    FilterSureView filterSureView;

    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private final String[] mTitles = {"巡护记录", "签到记录"};

    private AllTrackRecordFragment trackRecordFragment;
    private boolean departFlag = false; //记录部门是否展开
    private String beginTime = null;
    private String endTime = null;
    private DepartmentAdapter departmentAdapter;
    private List<DeptNameBean.ListBean> departBeans;
    private List<DeptNameBean.ListBean> myDepartBeans;
    private DeptNameBean deptNameBean;
    private List<String> deptIdList = null;
    private AllSignInRecordFragment signInRecordFragment;
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_record;
    }

    @Override
    protected void initView() {
        setModuleTitle("历史记录");
        setTitleBarBackground(getResources().getDrawable(com.mingtu.center.R.drawable.titlebar_line_bottom));
        showTopRightImg(R.mipmap.icon_filte);

    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        int type = getIntent().getIntExtra("type", 0);


        //-----------------------巡护记录------------------
        //保护站列表
        FlexboxLayoutManager flm1 = new FlexboxLayoutManager(this);
        flm1.setFlexWrap(FlexWrap.WRAP);
        flm1.setFlexDirection(FlexDirection.ROW);
        flm1.setAlignItems(AlignItems.STRETCH);
        flm1.setJustifyContent(JustifyContent.FLEX_START);
        recyclerDepart.setLayoutManager(flm1);

        departmentAdapter = new DepartmentAdapter(context, null);
        recyclerDepart.setAdapter(departmentAdapter);


        //从首页跳转过来，查看当日的记录
        String flag = getIntent().getStringExtra("flag");
        if (!StringUtils.isEmpty(flag)) {
            Calendar startCalendar = Calendar.getInstance(); //Calendar类型的数据之后 将时间的时分秒数据重置为0,然后再转为Date型数据
            int yearS = startCalendar.get(Calendar.YEAR);
            int monthS = startCalendar.get(Calendar.MONTH);
            int dayS = startCalendar.get(Calendar.DAY_OF_MONTH);


            startCalendar.set(yearS, monthS, dayS, 0, 0, 0);
            Date MyDate = startCalendar.getTime();
            String startTime = UIUtils.getTime(MyDate);


            beginTime = UIUtils.getTime3(MyDate);
            timeFilterTime.setStartTime(startTime);


            Calendar endCalendar = Calendar.getInstance(); //Calendar类型的数据之后 将时间的时分秒数据重置为0,然后再转为Date型数据
            int year = endCalendar.get(Calendar.YEAR);
            int month = endCalendar.get(Calendar.MONTH);
            int day = endCalendar.get(Calendar.DAY_OF_MONTH);

            int hour = endCalendar.get(Calendar.HOUR_OF_DAY);
            int minute = endCalendar.get(Calendar.MINUTE);
            int second = endCalendar.get(Calendar.SECOND);

            startCalendar.set(year, month, day, hour, minute, second);
            Date endDate = startCalendar.getTime();

            endTime = UIUtils.getTime3(endDate);


            String myEndTime = UIUtils.getTime(endDate);
            timeFilterTime.setEndTime(myEndTime);


            trackRecordFragment = AllTrackRecordFragment.getInstance(beginTime, endTime);
            signInRecordFragment = AllSignInRecordFragment.getInstance(beginTime, endTime);
            mFragments.add(trackRecordFragment);
            mFragments.add(signInRecordFragment);


        } else {
            trackRecordFragment = AllTrackRecordFragment.getInstance();
            signInRecordFragment = AllSignInRecordFragment.getInstance();
            mFragments.add(trackRecordFragment);
            mFragments.add(signInRecordFragment);
        }

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i]));
        }

        commonTab.setTextBold(1);
        commonTab.setTabData(mTabEntities);
        commonTab.setCurrentTab(type);
        commonTab.setOnTabSelectListener(new MyOnTabSelectListener());

        viewPager.setOffscreenPageLimit(2);//需要设置此值
        viewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), mFragments));
        viewPager.addOnPageChangeListener(new MyOnPageChangeListener());
        viewPager.setCurrentItem(type);

        timeFilterTime.setOnTimeResultListener(new TimeFilterView.OnTimeResultListener() {
            @Override
            public void onResult(Date startDate, Date endDate) {
                beginTime = UIUtils.getTime3(startDate);
                endTime = UIUtils.getTime3(endDate);
            }
        });

        filterCancleView.setOnClickListener(new FilterCancleView.OnClickListener() {
            @Override
            public void onClickCancel() {
                closeDrawers();
            }
        });

        filterSureView.setOnClickListener(new FilterSureView.OnClickListener() {
            @Override
            public void onClickReset() {
                closeDrawers();
                resetData();
                CalendarPickerUtils.getInstance().resetData();
            }

            @Override
            public void onClickSure() {
                closeDrawers();
                deptIdList = departmentAdapter.getDeptIdList();
                trackRecordFragment.setBeginTime(beginTime);
                trackRecordFragment.setEndTime(endTime);
                trackRecordFragment.setDeptIdList(deptIdList);
                trackRecordFragment.getTrackRecordList(1);

                signInRecordFragment.setBeginTime(beginTime);
                signInRecordFragment.setEndTime(endTime);
                signInRecordFragment.setDeptIdList(deptIdList);
                signInRecordFragment.getSignInRecord(1);
            }
        });


    }

    @Override
    protected void getData() {
        getDeptList();
    }

    @Override
    protected void onClickTitlebarRight(View view) {
        super.onClickTitlebarRight(view);
        boolean isOpen = drawerLayout.isDrawerOpen(layoutRightDrawer);
        if (isOpen) {
            closeDrawers();
        } else {
            openDrawer();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.layout_arrow_depart})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_arrow_depart:
                if (departFlag) { //默认为false,收起状态
                    departFlag = false;
                    tvFoldDepart.setText("展开");
                    departmentAdapter.upData(myDepartBeans);
                } else {
                    departFlag = true;
                    tvFoldDepart.setText("收起");
                    departmentAdapter.upData(departBeans);
                }
                break;

        }

    }

    private void resetData() {
        departmentAdapter.resetData();
        beginTime = null;
        endTime = null;
        deptIdList = null;

        timeFilterTime.resetData();

        trackRecordFragment.setBeginTime(beginTime);
        trackRecordFragment.setEndTime(endTime);
        trackRecordFragment.setDeptIdList(deptIdList);
        trackRecordFragment.getTrackRecordList(1);

        signInRecordFragment.setBeginTime(beginTime);
        signInRecordFragment.setEndTime(endTime);
        signInRecordFragment.setDeptIdList(deptIdList);
        signInRecordFragment.getSignInRecord(1);
    }

    @Subscribe
    public void onStringEvent(MyEventBus event) {
        //处理完之后刷新数据
        String message = event.getMessgae();
        if (message.equals(MyConstant.REFRESH_TOP_TRACK_DATA)) {
            String result = event.getParam();
            Gson gson = GsonFactory.getSingletonGson();
            AllTrackRecordBean.DataBean.StaticsBean staticsBean = new AllTrackRecordBean.DataBean.StaticsBean();
            staticsBean = gson.fromJson(result, AllTrackRecordBean.DataBean.StaticsBean.class);
            int totalMileage = staticsBean.getTotalMileage();
            String duration = staticsBean.getTotalDuration();
            String totalCount = staticsBean.getTotalCount();
            String clockNum = staticsBean.getClockNum();


            tvTotalMileage.setText(totalMileage + "");


            if (!StringUtils.isEmpty(totalCount)) {
                tvTotalDayNum.setText(totalCount + "");
            } else {
                tvTotalDayNum.setText("0");
            }

            if (!StringUtils.isEmpty(clockNum)) {
                tvTotalSignInNum.setText(clockNum + "");
            } else {
                tvTotalSignInNum.setText("0");
            }

            if (!StringUtils.isEmpty(duration)) {
                long d = 0;
                if (duration.indexOf(".") != -1) {
                    String array[] = duration.split("\\.");
                    d = Long.parseLong(array[0]);
                } else {
                    d = Long.parseLong(duration);
                }
                tvTotalTime.setText(MyUtills.formatSeconds2(d));
            } else {
                tvTotalTime.setText("0");
            }

        }

    }


    //点击tab 监听
    private class MyOnTabSelectListener implements OnTabSelectListener {

        @Override
        public void onTabSelect(int position) {
            viewPager.setCurrentItem(position);
        }

        @Override
        public void onTabReselect(int position) {

        }
    }


    private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            commonTab.setCurrentTab(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }

    }

    /**
     * 关闭侧边栏
     */
    public void closeDrawers() {
        drawerLayout.closeDrawer(layoutRightDrawer, true);
    }

    /**
     * 打开侧边栏
     */
    public void openDrawer() {
        drawerLayout.openDrawer(layoutRightDrawer);
    }

    /**
     * 获得巡护记录的部门名字数据
     */
    private void getDeptList() {
        OkGo.<String>post(Constant.getInstance().POST_DEPT_LIST2)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                deptNameBean = new DeptNameBean();
                                deptNameBean = gson.fromJson(result, DeptNameBean.class);

                                if (deptNameBean != null) {
                                    departBeans = deptNameBean.getList();

                                    if (departBeans != null) {
                                        if (departBeans.size() > 0) {

                                            if (departBeans.size() > 6) {
                                                //数据大于6的时候，取前6条数据，有展开收回操作
                                                myDepartBeans = departBeans.subList(0, 6);
                                                departmentAdapter.upData(myDepartBeans);
                                                layoutArrowDepart.setVisibility(View.VISIBLE);

                                            } else {
                                                //数据个数小与6的时候，展开视图隐藏
                                                departmentAdapter.upData(departBeans);
                                                layoutArrowDepart.setVisibility(View.GONE);
                                            }

                                        }
                                    }
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }

}